package com.beiding.fastmock.fram;

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 丁常磊
 * @date 2021/7/22 18:03
 */

public class ScriptInterceptor implements HandlerInterceptor {

    private ScriptObjectMirror obj;

    public ScriptInterceptor(ScriptObjectMirror obj) {
        this.obj = obj;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (obj.containsKey("preHandle")) {
            Object preHandle = obj.callMember("preHandle", request, response, handler);
            if (preHandle instanceof Boolean) {
                return (boolean) preHandle;
            }
            return false;
        } else {
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (obj.containsKey("postHandle")) {
            obj.callMember("postHandle", request, response, handler, modelAndView);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (obj.containsKey("afterCompletion")) {
            obj.callMember("afterCompletion", request, response, handler, ex);
        }
    }
}
